// app.js
var websocket = require('./utils/websocket') 
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log('小程序初始化，正在获取token')
        console.log(res.code)
        wx.request({
          url: this.globalData.apiUrl + '/authorization/getTokenByCode/' + res.code,
          method: 'GET',
          success: (res) => {
            wx.setStorageSync('token', res.data.data)
            console.log('token的值为' + wx.getStorageSync('token'))
          }
        })
      }
    })
    //获取系统信息，配置导航栏高度，直接用<cu-custom bgColor="bg-gradual-blue">不会生效，要先把高度配置好
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    apiUrl: "https://ip/portal",//后端接口请求地址，测试阶段可以使用http上线必须使用https
		fileApi: "https://ip/file",//文件上传用接口地址
		apiService: "https://ip:8000"
  },

  //封装wx.request
  //此函数实现的使用wx.request()发送请求
  after_request(params) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: params.url,
        method: params.method || 'GET',
        data: params.data || {},
        header: params.header,
        success(res) {
          resolve(res)
        },
        fail: function (e) {
          reject(e)
        }
      })
    })
  },
  openid() {
    wx.showLoading({
      title: '正在获取合法请求',
    })
    return new Promise((resolve, reject) => {
      let that = this
      wx.login({
        timeout: 3000,
        success(res) {
          if (res.code) {
            wx.request({
              url: 'https://localhost:8081/authorization/getTokenByCode/' + res.code,
              method: "GET",
              success(res) {
                console.log('res=' + res.data.obj)
                wx.setStorageSync('token', res.data.obj)
                resolve(res)
              },
              fail: function (e) {
                console.log('e=' + e)
                reject(e)
              }
            })
          }
        }
      })
    })
  },

  //此函数实现的是在发送网络请求前，查看本地是否含有token，若存在则添加在请求头中，若不存在去执行openid()函数获取到token后再去发送网络请求
  request(params) {
    var that = this
    if (params.method) {
      params.method = params.method.toUpperCase()
    }
    if (wx.getStorageSync('token') != null) {
      if (params.header) {
        params.header.token = wx.getStorageSync('token')
      } else {
        params.header = {}
        params.header.token = wx.getStorageSync('token')
      }
      var request = that.after_request(params)
    } else {
      console.log('token失效' + wx.getStorageSync('token'))
      var request = that.openid().then(res => {
        if (params.header) {
          params.header.token = wx.getStorageSync('token')
        } else {
          params.header = {}
          params.header.token = wx.getStorageSync('token')
        }
        return that.after_request(params)
      })
    }
    return request
  },
})